from datetime import datetime
from app import db
from werkzeug.security import generate_password_hash, check_password_hash


class Admin(db.Model):
    """管理员模型"""
    __tablename__ = 'admin'
    
    id = db.Column(db.Integer, primary_key=True)
    admin_name = db.Column(db.String(50), nullable=False, comment='管理员名称')
    username = db.Column(db.String(50), unique=True, nullable=False, comment='登录账号')
    password_hash = db.Column(db.String(128), nullable=False, comment='密码哈希')
    department_id = db.Column(db.Integer, db.ForeignKey('department.id'), nullable=True, comment='部门ID')
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'), nullable=False, comment='角色ID')
    status = db.Column(db.Boolean, default=True, comment='状态(True=正常,False=禁用)')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    department = db.relationship('Department', backref='admins')
    role = db.relationship('Role', backref='admins')
    
    def set_password(self, password):
        """设置密码"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    def to_dict(self):
        """转换为字典"""
        # 获取角色的权限字符
        rolekey = []
        if self.role and self.role.key:
            rolekey = [self.role.key]
        
        return {
            'id': self.id,
            'name': self.admin_name,  # 前端期望的字段名
            'admin_name': self.admin_name,  # 保持兼容性
            'username': self.username,
            'department_id': self.department_id,
            'department_name': self.department.name if self.department else None,
            'role_id': self.role_id,
            'role_name': self.role.name if self.role else None,
            'rolekey': rolekey,  # 前端期望的权限字符数组
            'status': self.status,
            'is_active': self.status,  # 前端期望的字段名
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'create_datetime': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,  # 前端期望的字段名
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None
        } 